<template>
	<view class="Login_box">
		<view class="bg column center">
			<image src="../../static/img/ca.png" class="bg-image"></image>
			<view class="TextBox">
				<view class="Text">
					欢迎来到计算机协会
				</view>
				<view class="Text1">
					CA报修小程序需要您的授权
				</view>
				<view class="Text2">
					CA报修小程序不会将您的信息提供给第三方
				</view>
			</view>
			<view class="Buttom">
				<button @click="handleLogin" type="primary" lang="zh_CN">
				  微信授权登录
				</button>
				
				<view v-if="loading" class="loading">
					<!-- <text>登录中...</text> -->
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getCode
	} from '@/api/login.js'
	import {
		request
	} from '@/common/js/request.js'
	import API from '@/api/api.js'
	import '@/common/css/login.scss'
	export default {
		data() {
			return {
				canIUseGetUserProfile: false,
				loading: false // 加载状态
			}
		},
		methods:{
			async handleLogin() {
				try {
					this.loading = true;
					uni.showLoading({
						title: '登录中'
					});
			
					// 设置请求超时时间，例如 10 秒
					const timeout = new Promise((_, reject) => setTimeout(() => reject(new Error('请求超时')), 10000));
			
					// 使用 Promise.race 来进行超时控制
					const js_code = await getCode(); // 获取 js_code
			
					const res = await Promise.race([
						request({
							url: '/user/register',
							method: 'POST',
							data: {
								"code": js_code
							}
						}),
						timeout // 超时控制
					]);
					// console.log(res)
					const token = res.data;
			
					uni.setStorageSync("token", token);
			
					uni.showToast({
						title: '登录成功',
						icon: 'success',
						mask: true,
					});
			
					const userinfo = await API.getUserInfo(token)
					if (userinfo && userinfo.data.realname && userinfo.data.dormmun &&
						userinfo.data.phone && userinfo.data.stunum) {
						uni.switchTab({
							url: '/pages/index/index'
						})
					} else {
						uni.redirectTo({
							url: '/pages/user-info/user-info'
						})
					}
			
				} catch (error) {
					if (error.message === '请求超时') {
						uni.showToast({
							title: '请求超时',
							icon: 'none',
							mask: true,
						});
					} else {
						uni.showToast({
							title: '登录失败',
							icon: 'none',
							mask: true,
						});
					}
				} finally {
					this.loading = false;
					uni.hideLoading();
				}
			}
		}
	}
</script>

<style>

</style>